<?php
namespace App\Model;

use App\Model\BaseModel;

/**
 * 取回报价相关
 * OutTradeModel.php
 * @author zhouqiang
 * @date 2018/05/11
 */
class OutTradeModel extends BaseModel 
{
	protected $table = 'out_trade';

	protected $primaryKey = 'out_trade_id';

	public static $tradeStatusMap = [
		'time-out'	=> -100, // 超时
		'error-6'	=> -6, // steam服务器不稳定
		'error-5'	=> -5, // 发送报价过多
		'error-4'	=> -4, // 无法交易，隐私或限制
		'error-3'	=> -3, // 交易链接失效，库存超限，限制
		'error-2'	=> -2, // 物品已取回
		'reading'	=> -1, // 准备
		'creating'	=> 9, // 已发起报价
		'waiting'	=> 2, // 已确认报价
		'success'	=> 3, // 报价成功
		'cancel'	=> 6, // 取消报价
		'deny'	=> 7, // 拒绝报价
	];

	public function outTradeDetail()
	{
		return $this->hasMany('App\Model\OutTradeDetailModel', 'out_trade_id', 'out_trade_id');
	}

	public function bots()
	{
		return $this->hasOne('App\Model\BotsModel', 'bot_id', 'bot_id');
	}

	/**
	 * 获取准备发起报价的信息
	 * @return array
	 */
	public static function getOutTradeByReading()
	{
		$where = array(
			'tradeoffer_status' => self::$tradeStatusMap['reading'],
		);

		$query = static::whereHas('bots', function($q)
		{
			$q->where('client_no' , '=', env('APP_NO'));
		});

		$result = $query->where($where)->with('outTradeDetail')->get();

		return !empty($result) ? $result->toArray() : [];
	}

	/**
	 * 记录报价ID
	 * @param  int $outTradeId 报价订单ID
	 * @param  int $tradeofferId 报价ID
	 * @return bool
	 */
	public static function updateOutTradeByOutTradeId($outTradeId, $tradeofferId)
	{
		$where = array(
			'out_trade_id' => $outTradeId,
		);

		$field = array(
			'tradeoffer_status' => self::$tradeStatusMap['creating'],
			'tradeoffer_id' => $tradeofferId,
		);

		return static::where($where)->update($field);
	}

	/**
	 * 修改报价状态
	 * @param  int $outTradeId 报价订单ID
	 * @param  int $tradeofferStatus 报价状态
	 * @return bool
	 */
	public static function updateOutTradeState($outTradeId, $tradeofferStatus)
	{
		$where = array(
			'out_trade_id' => $outTradeId,
		);

		$field = array(
			'tradeoffer_status' => $tradeofferStatus,
		);

		return static::where($where)->update($field);
	}

	/**
	 * 获取创建中报价
	 * @return array
	 */
	public static function getOutTradeByCreating()
	{
		$where = array(
			'tradeoffer_status' => self::$tradeStatusMap['creating'],
			'conf_id' => '',
			'conf_key' => '',
		);

		$query = static::whereHas('bots', function($q)
		{
			$q->where('client_no' , '=', env('APP_NO'));
		});

		$result = $query->where($where)->get();

		return !empty($result) ? $result->toArray() : [];
	}

	/**
	 * 获取报价信息
	 * @param  int $tradeofferId 报价ID
	 * @return array
	 */
	public static function getOutTradeByTradeId($tradeofferId)
	{
		$where = array(
			'tradeoffer_id' => $tradeofferId,
		);

		$result = static::where($where)->first();

		return $result ? $result->toArray() : [];
	}

	/**
	 * 修改报价信息
	 * @param  int $tradeofferId 报价ID
	 * @param  string $confId
	 * @param  string $confKey
	 * @return bool
	 */
	public static function updateOutTradeByTradeId($tradeOfferId, $confId, $confKey)
	{
		$where = array(
			'tradeoffer_id' => $tradeOfferId,
		);

		$field = array(
			'conf_id' => $confId,
			'conf_key' => $confKey,
		);

		return static::where($where)->update($field);
	}

    public static  function createTradeOffer($data){
        $connection = (new self())->getConnection();
        $connection->beginTransaction();
        try {
            $outTrade = new self ();
            $outTrade->bot_id = $data['bot_id'];
            $outTrade->steam_id = $data['steam_id'];
            $outTrade->steam_token = $data['steam_token'];
            $outTrade->quantity = $data['quantity'];
            $outTrade->queue_name = $data['queue_name'];
            $outTrade->tradeoffer_id = $data['tradeoffer_id'];
            $outTrade->tradeoffer = $data['tradeoffer'];
            $outTrade->tradeoffer_status = self::$tradeStatusMap['reading'];
            if(!$outTrade->save()){
                throw new \Exception();
            }
            $outTradeId = $outTrade->out_trade_id;
            if(!OutTradeDetailModel::createTradeDetail($outTradeId,$data['detail_items'])){
                throw new \Exception();
            }
            $connection->commit();
            return $outTradeId;
        }catch(\Exception $e) {
            $connection->rollBack();
            return false;
        }
    }

	/**
	 * 获取等待确认的报价
	 * @return array
	 */
	public static function getOutTradeByWaitAccept()
	{
		$where = array(
			'tradeoffer_status' => self::$tradeStatusMap['creating'],
		);

		$query = static::whereHas('bots', function($q)
		{
			$q->where('client_no' , '=', env('APP_NO'));
		});

		$result = $query->where($where)->where('conf_id', '<>', '')->where('conf_key', '<>', '')->get();

		return !empty($result) ? $result->toArray() : [];
	}

	/**
	 * 获取待检查的报价状态
	 * @return array
	 */
	public static function getOutTradeByCheckAll()
	{
		$whereIn = array(
			self::$tradeStatusMap['creating'],
			self::$tradeStatusMap['waiting'],
			self::$tradeStatusMap['reading'],
		);

		$result = static::whereIn('tradeoffer_status', $whereIn)->get();

		return !empty($result) ? $result->toArray() : [];
	}

    /**
     * 获取报价信息
     * @param  int $tradeofferId 报价ID
     * @return array
     */
    public static function getOutTradeByOutTradeId($outTradeId)
    {
        $where = array(
            'out_trade_id' => $outTradeId,
        );

        $result = static::where($where)->first();

        return $result ? $result->toArray() : [];
    }
}